<!--
 * @Author: wwssaabb
 * @Date: 2021-08-17 10:46:11
 * @LastEditTime: 2021-08-17 11:05:00
 * @FilePath: \axios_demo\base\cancel.html
-->
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
  <title>Document</title>
</head>

<body>
  <div class="container">
    <h2 class="page-header">基本使用</h2>
    <button class="btn btn-primary">发送GET请求</button>
    <button class="btn btn-warning">取消请求</button>
  </div>

  <script>
    let buts=document.querySelectorAll('button')

    //声明变量
    let cancel=null

    //发送请求
    buts[0].onclick=()=>{
      if(cancel!==null){
        cancel()
      }
      axios({method:'GET',url:'http://localhost:3000/posts',cancelToken:new axios.CancelToken(v=>cancel=v)}).then(res=>console.log(res))}
      

    //绑带取消事件
    buts[1].onclick=()=>{
      cancel()
      cancel=null
    }
  </script>
</body>

</html>